<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017-06-20
 * Time: 13:47
 */

namespace App\Tool;


use Illuminate\Support\Facades\Cache;

class Tool
{
	/*
	 * ajax返回
	 * @param   $status     int     状态码
	 * @param   $msg        string     提示字符
	 */
	static public function ajaxReturn ($status = 200, $msg = '')
	{
		return response()->json([
			'code' => $status,
			'msg' => $msg
		]);
	}

	/*
	 * 处理前端页面排序的class
	 * @param   string  $field  要排序的字段
	 * @param   string  $order  排序顺序
	 * return   array   返回该类的排序数组
	 */
	static public function sortClass($field, $order = 'asc')
	{
		$list = array();
		$list[$field] = $field;
		if ($order == 'desc') {
			$list['class'] = 'glyphicon glyphicon-chevron-down';
			$list['order'] = 'asc';
		} else {
			$list['class'] = 'glyphicon glyphicon-chevron-up';
			$list['order'] = 'desc';
		}

		return $list;
	}


	/*
	 * 检测缓存key是否存在
	 * @param   string  $key    缓存键
	 * @param   string  $store  缓存类型
	 * return   bool    存在返回true失败返回false
	 */
	static public function hasCache($key, $store = 'redis')
	{
		if (Cache::store($store)->has($key)) {
			return true;
		} else {
			return false;
		}
	}

	/*
	 * @param   array   $list   要无限级分类的数组
	 * return   array   $tree
	 */
	static public function tree($list,$category_id = 0,$level = 0){
		static $tree = [];
		foreach ($list as $row) {
			if ($row['parent_id'] == $category_id){
				$row['level'] = $level;
				$tree[] = $row;
				self::tree($list,$row['id'],$level+1);
			}
		}
		return $tree;
	}

	/*
	 * 查找后代childId是否是parentId的后代
	 * @param   int     $parentId   父id
	 * @param   int     $currId     当前id
	 * @param   int     $list       条目总列表
	 */
	static public function checkChild ($parentId, $currId, $list)
	{
		if ($parentId == 0) {
			return true;
		} elseif ($parentId == $currId) {
			return false;
		}

		//获取当前选择的父分类的父分类id
		foreach ($list as $item) {
			if ($item['id'] == $parentId) {
				$parentId = $item['parent_id'];
			}
		}

		return self::checkChild($parentId, $currId, $list);

	}

	/*
	 * 获取某条目的后代
	 * @param   int     $idList     要查找后代的id
	 * @param   int     $itemList       条目总列表
	 */
	static public function getSon ($idList, $itemList)
	{
		static $sonId = array();
		foreach ($idList as $id) {
			foreach ($itemList as $item) {
				if ($id == $item['parent_id']) {
					$sonId[] = $item['id'];
					self::getSon([$item['id']], $itemList);
				}
			}
		}
		return $sonId;
	}
}